package com.ithinks.flow.iot.tb.mqtt.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;

/**
 * @Description
 * @ClassName SheduleTask
 * @Author MR.LI
 * @date 2020.12.21 18:59
 */
@Configuration
@EnableScheduling
public class SheduleTask {
    @Value("${spring.mqtt.paramKeys}")
    private String paramKeys;

    @Autowired
    MqttGateway mqttGateway;

    private static final Logger LOGGER = LoggerFactory.getLogger(SheduleTask.class);
    //3.添加定时任务
    @Scheduled(cron = "0/40 * * * * ?")
    private void configureTasks() {

        LOGGER.info("paramkeys:{}",paramKeys);

        String msgJson = makeMsgJson(paramKeys);

        mqttGateway.sendToMqtt(msgJson);
    }

    public BigDecimal makeRandom(float max, float min, int scale){
        BigDecimal cha = new BigDecimal(Math.random() * (max-min) + min);
        return cha.setScale(scale, BigDecimal.ROUND_HALF_UP);//保留 scale 位小数，并四舍五入
    }

    public String makeMsgJson(String paramKeys){

        String[] params = paramKeys.split(",");

        StringBuilder msgTemplate = new StringBuilder();
        msgTemplate.append("{");

        for (int i =0; i<params.length; i++){
            if(i < (params.length-1)){
                LOGGER.info("i:{}",i);
                msgTemplate.append(params[i]).append(":").append(makeRandom(100,0,2)).append(",");
            }else if(i == (params.length-1))
            {
                msgTemplate.append(params[i]).append(":").append(makeRandom(100,0,2)).append(",");
                msgTemplate.append("ts:").append(System.currentTimeMillis());
            }
        }

        msgTemplate.append("}");
        LOGGER.info("模拟数据：{}",msgTemplate.toString());
        return msgTemplate.toString();

    }
}
